package team.tunan.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Date 2022/7/9
 * @Author ztc
 * @Description TODO
 */

public class UploadUtils {

    //定义一个目标路径，就是我们要把图片上传到的位置
//    private static final String BASE_PATH="D:\\idea_java_projects\\online-vote\\target\\classes\\static\\img";
//    private static final String BASE_PATH = "C:\\Users\\Lenovo\\Desktop\\online-vote\\target\\classes\\static\\img";
    private static final String BASE_PATH = "D:\\peoject\\vote\\src\\main\\resources\\static\\img";

    //定义一个图片回显的路径
    private static final String SERVER_PATH = "http://localhost:8087/static/img/";

    public static String upload(MultipartFile file) {

        //获得上传文件的名称
        String filename = file.getOriginalFilename();
        //为了保证图片在服务器中名字的唯一性，这个是我呢要用UUID来对filename进行改写
        String uuid = UUID.randomUUID().toString().replace("_", "");
        //将生成的UIDD和filename进行拼接
        String newFilename = uuid + "_" + filename;
        //创建一个文件实例对象
        File dir = new File(BASE_PATH);
        if(!dir.exists()){
            dir.mkdirs();
        }
        File image = new File(BASE_PATH, newFilename);
        //对这个文件进行上传操作
        try {
            file.transferTo(image);
        } catch (IOException e) {
            return null;
        }
        System.out.println(SERVER_PATH + newFilename);
        return SERVER_PATH + newFilename;
    }


}
